﻿using System;
using System.Management.Automation;
using System.Runtime.InteropServices;
using Microsoft.SharePoint.PowerShell;

namespace CodeCounsel.SharePoint2010.DigiD.Cmdlets
{
    [SPCmdlet(RequireLocalFarmExist = true, RequireUserFarmAdmin = true)]
    [Cmdlet(VerbsCommon.Copy, "DigiDSettings")]
    public class CopyDigiDSettingsCmdlet : SPNewCmdletBase<DigiDSettings>
    {
        [Parameter(Mandatory = true, Position = 0, ValueFromPipeline=true)]
        public DigiDSettingsPipeBind Identity { get; set; }

        [Parameter(Mandatory = true, Position = 1)]
        public string Name { get; set; }

        [Parameter(Mandatory = true, Position = 2)]
        public Uri SiteUrl { get; set; }

        [Parameter(Mandatory = false, Position = 3)]
        public Uri ServerUrl { get; set; }

        [Parameter(Mandatory = false, Position = 4)]
        public string ServerID { get; set; }

        [Parameter(Mandatory = false, Position = 5)]
        public string ApplicationID { get; set; }

        [Parameter(Mandatory = false, Position = 6)]
        public SecurityLevel SecurityLevel { get; set; }

        [Parameter(Mandatory = false, Position = 7)]
        public string SharedSecret { get; set; }

        protected override void InternalValidate()
        {
            DataObject = Identity.Read();
            DigiDSettings settings = DigiDService.Local.DigiDSettings[Name];
            if (settings != null)
            {
                throw new ArgumentException("Name already in use.");
            }
            base.InternalValidate();
        }

        protected override DigiDSettings CreateDataObject()
        {
            DigiDSettings settings = DigiDService.Local.DigiDSettings.Add(Name);
            settings.ServerUrl = ServerUrl == null ? DataObject.ServerUrl : ServerUrl;
            settings.ServerID = String.IsNullOrEmpty(ServerID) ? DataObject.ServerID : ServerID;
            settings.ApplicationID = String.IsNullOrEmpty(ApplicationID) ? DataObject.ApplicationID : ApplicationID;
            settings.SecurityLevel = SecurityLevel == SecurityLevel.NotSet ? DataObject.SecurityLevel : SecurityLevel;
            settings.SharedSecret = String.IsNullOrEmpty(SharedSecret) ? DataObject.SharedSecret : SharedSecret;
            settings.SiteUrl = SiteUrl == null ? DataObject.SiteUrl : SiteUrl;
            settings.Update();
            return settings;
        }
    }
}
